package logic

import (
	"Junior_two/subject/common"
	"Junior_two/subject/order/orderrpc/dao"
	"Junior_two/subject/pay/payrpc/internal/svc"
	"Junior_two/subject/pay/payrpc/pb/payRpc"
	"context"
	"fmt"
	"github.com/astaxie/beego/logs"
	"github.com/smartwalle/alipay/v3"
	"net/http"
	"strconv"

	"github.com/zeromicro/go-zero/core/logx"
)

type PayLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPayLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PayLogic {
	return &PayLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

var (
	AppId        string
	PrivateKey   string
	AliPublicKey string
	client       *alipay.Client
)

func init() {
	AppId = common.AppId
	PrivateKey = common.PrivateKey
	AliPublicKey = common.AliPublicKey
	logs.Info(AppId)
	logs.Info(PrivateKey)
	logs.Info(AliPublicKey)
	client, _ = alipay.New(AppId, PrivateKey, false)
	client.LoadAlipayCertPublicKey(AliPublicKey)
}

func (l *PayLogic) Pay(in *payRpc.PayRequest) (*payRpc.PayResponse, error) {
	// todo: add your logic here and delete this line
	orderId := in.OrderId
	subject := in.Subject
	//根据订单id 编号 查找 本订单需要支付多少钱
	o := dao.GetDataByOrderId(orderId)
	totalAmount := o.TotalAmount
	t := fmt.Sprintf("%.2f", totalAmount)
	logs.Info(subject)
	fmt.Println(t)
	//调用支付接口
	payUrl := common.AliPay(subject, strconv.FormatInt(o.OrderNum, 10), client, t)
	return &payRpc.PayResponse{
		Msg:  "请访问支付接口",
		Code: http.StatusOK,
		Data: payUrl,
	}, nil
}
